trigger upsertContacts on Visa_History__c (after delete, after insert, after update) {

/* The trigger upsert the Contacts whenever the Visa History
   Record gets inserted, deleted or modified. */

    Set<id> Cons = new Set<id>();

    List<Contact> ContactsToBeUpserted = new List<Contact>();
    // creating a set of Ids for Contacts 
    if (Trigger.isInsert || Trigger.isUpdate) {
        for (Visa_History__c item : Trigger.new) {
            if(item.Visa_Holder__c != null)
                Cons.add(item.Visa_Holder__c);
               
        }
    }
     //  If the Visa History is being deleted, then the associated Contact needs to be updated.     
    // If the Visa History is being updated, then both the old and new Contacts are processed.
      
    if (Trigger.isUpdate || Trigger.isDelete)
    {
     for (Visa_History__c item : Trigger.old){
          if(item.Visa_Holder__c != null)
            Cons.add(item.Visa_Holder__c); 
           } 
     }
     
    if (Trigger.isInsert || Trigger.isUpdate || Trigger.isDelete) {
    if(Cons != null) {   
     //Creating the list of contacts to be upserted 
      ContactsToBeUpserted = [SELECT id FROM Contact WHERE ID in: Cons];             
     }
  //upserting the Contacts
    upsert(ContactsToBeUpserted); 
   } 
}